import { RouteRecordRaw, createRouter, createWebHistory } from "vue-router";
import { basicRoutes, basicRoutesName, NOT_FOUND_ROUTE } from "./routes";
import { setupRouterGuard } from "./guard";
import type { App } from "vue";
import { token, isNullOrWhitespace } from "@/utils";
import { useUserStore, useRouterStore } from "@/store";

export const router = createRouter({
  history: createWebHistory("/"),
  routes: <RouteRecordRaw[]>basicRoutes,
  scrollBehavior() {
    return { left: 0, top: 0 };
  },
});

/** setup vue router */
export const setupRouter = async (app: App<Element>) => {
  await addDynamicRoutes();
  setupRouterGuard(router);
  app.use(router);
};

export const addDynamicRoutes = async () => {
  const tokenStr = token.get();

  // 没有token情况
  if (isNullOrWhitespace(tokenStr)) {
    router.addRoute(NOT_FOUND_ROUTE as RouteRecordRaw);
    return;
  }

  // 有token的情况
  const userStore = useUserStore();
  await userStore.getUserInfo();

  if (!userStore.isLogin) {
    window.$message.error("Token已过期，请重新登录");
    userStore.reLogin();
    return;
  }

  // 获取动态路由
  const routerStore = useRouterStore();
  const permsRoutes = await routerStore.getPermsRoutes();

  // 添加动态路由
  permsRoutes.forEach((route) => {
    if (router.hasRoute(route.name)) {
      console.error("存在重复的router：", route);
    } else {
      router.addRoute(route as RouteRecordRaw);
    }
  });

  // 将未定义路由匹配放置最后
  if (router.hasRoute(NOT_FOUND_ROUTE.name)) {
    router.removeRoute(NOT_FOUND_ROUTE.name);
  }
  router.addRoute(NOT_FOUND_ROUTE as RouteRecordRaw);
};

// 删除动态路由
export const resetRouter = async () => {
  router.getRoutes().forEach((route) => {
    const name = route.name as string;
    if (!basicRoutesName.includes(name)) {
      router.removeRoute(name);
    }
  });
};
